package com.googlecode.androidkurskoblenz.discovertest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;

import org.apache.http.conn.util.InetAddressUtils;

import android.app.Activity;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{
	private class ReaderThread extends Thread
	{
		public ReaderThread()
		{
			super("ReaderThread");
			
			this.start();
		}
		
		@Override
		public void run()
		{
			super.run();
			
			try
			{
				mSocket = new ServerSocket();
				mSocket.bind(null);
				
				DatagramSocket broadcast = new DatagramSocket();
				broadcast.setBroadcast(true);
				
				ByteBuffer data = ByteBuffer.allocate(4);
				data.putInt(mSocket.getLocalPort());
				
				Socket client;
				byte[] buffer = new byte[50];
				
				DatagramPacket packet = new DatagramPacket(data.array(), data.capacity(),
					InetAddress.getByName("255.255.255.255"), DISCOVER_PORT);
				broadcast.send(packet);
				
				Looper.prepare();
				
				client = mSocket.accept();
				client.getInputStream().read(buffer);
				
				final String str = new String(buffer);
				
				runOnUiThread(new Runnable()
				{
					public void run()
					{
						TextView tv = (TextView) findViewById(R.id.textView1);
						tv.setText(str);
					}
				});
			}
			catch(IOException e)
			{
				e.printStackTrace();
				onConnectionError();
			}
		}
	}
	private static final int DISCOVER_PORT = 54038;
	private ReaderThread mThread;
	
	public void btnClick(View v)
	{
		mThread = new ReaderThread();
	}
	
	public ServerSocket mSocket;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	
	public void onConnectionError()
	{
		Log.i("receive", "error!");
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
}
